package com.example.hblog.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.hblog.module.pojo.User;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT token生成以及验证
 */


public class JWTUtils {

    private static String TOKEN = "z^$%edf4g/=3cv/c"; //密钥

    /**
     * 使用JWT生成token
     */
    public static String getToken(User user){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_WEEK,1);
        String token = JWT.create()
                .withClaim("name",user.getName())
                .withClaim("sign",user.getSign())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 验证token信息
     */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }

    /**
     * 验证token信息
     */
    public static Map<String,Object> verify1(String token){
        Map<String,Object> map = new HashMap<>();
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
        DecodedJWT verify = jwtVerifier.verify(token);
        String name = verify.getClaims().get("name").asString();
        String sign = verify.getClaims().get("sign").asString();
        map.put("name",name);
        map.put("sign",sign);
        return map;
    }

}
